﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Application.App;
using DTO;
using Infrastructure.Error;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OtherLib.TenXun;
using Utility;

namespace FacadeApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MiniController : ControllerBase
    {
        public WxMiniApplication wxMiniApplication { get; set; }
        public ILogger<MiniController> _logger { get; set; }

        /// <summary>
        /// 获取小程序Token信息
        /// </summary>
        /// <param name="wxCodeInfoInput"></param>
        /// <returns></returns>
        [AllowAnonymous, HttpPost]
        public ActionResult<UserLoginOutput> GetWxCodeInfo(WxCodeInfoInput wxCodeInfoInput)
        {
            string ipaddress = this.HttpContext.Connection.RemoteIpAddress.ToString();
            try
            {
                var json = WxMiniUtil.GetOpendidAndSessionkey(wxCodeInfoInput.wxCode);
                if (json.ContainsKey("errcode"))
                {
                    string errcode = Convert.ToString(json.Property("errcode").Value);
                    return this.FailResult(errcode);
                }
                var openId = Convert.ToString(json.Property("openid").Value);

                var loginInfo = wxMiniApplication.TryWxMiniLoginByOpenId(openId, ipaddress);

                if (loginInfo!=null)return this.Success(loginInfo);


                var session_key = Convert.ToString(json.Property("session_key").Value);
                var unionId = string.Empty;
                var phone = string.Empty;
                var headimg = string.Empty;
                var nickname = string.Empty;
                if (json.ContainsKey("UnionId")) unionId = Convert.ToString(json.Property("UnionId").Value);
                else
                {
                    string decryptedContent = EncryptorUtil.AESDecrypt(wxCodeInfoInput.encryptedData, wxCodeInfoInput.iv, session_key);
                    JObject jsonObject = (JObject)JsonConvert.DeserializeObject(decryptedContent);

                    //Console.WriteLine(decryptedContent);
                    unionId = Convert.ToString(jsonObject.Property("unionId").Value);
                    if (jsonObject.ContainsKey("purePhoneNumber")) phone = jsonObject.Value<string>("purePhoneNumber");
                    if (jsonObject.ContainsKey("avatarUrl")) headimg = Convert.ToString(jsonObject.Property("avatarUrl").Value);
                    if (jsonObject.ContainsKey("nickName")) nickname = Convert.ToString(jsonObject.Property("nickName").Value);
                    
                }

                var obj = new { openId, unionId, phone, headimg,session_key,nickname };

                

                return this.Success(EncryptorUtil.Encrypt(JsonConvert.SerializeObject(obj), "jbelmaxidvlrecnb", "5992038507950310"));
            }
            catch (BizException ex)
            {
                return this.FailResult(ex.data, ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                return this.FailResult(null, "系统繁忙，请稍后重试!");
            }
        }
        /// <summary>
        /// 登录小程序
        /// </summary>
        /// <param name="loginWxMiniInput"></param>
        /// <returns></returns>
        [AllowAnonymous, HttpPost]
        public ActionResult<UserLoginOutput> LoginWxMini(LoginWxMiniInput loginWxMiniInput)
        {
            string ipaddress = this.HttpContext.Connection.RemoteIpAddress.ToString();
            try
            {
                var decode = EncryptorUtil.Decrypt(loginWxMiniInput.Data, "jbelmaxidvlrecnb", "5992038507950310");
                var map = JsonConvert.DeserializeObject<IDictionary<string, string>>(decode);

                var openId = map["openId"];
                var unionId = map["unionId"];
                var headimg = map["headimg"];
                var session_key = map["session_key"];
                var nickname = map["nickname"];
                var phone = string.Empty;


                string decryptedContent = EncryptorUtil.AESDecrypt(loginWxMiniInput.encryptedData, loginWxMiniInput.iv, session_key);

                JObject jsonObject = (JObject)JsonConvert.DeserializeObject(decryptedContent);
                //Console.WriteLine(decryptedContent);
                phone = jsonObject.Value<string>("purePhoneNumber");

                var r = wxMiniApplication.WxMiniLogin(loginWxMiniInput.InvitationCode, phone, unionId, openId, headimg, nickname, ipaddress, decryptedContent);

                return this.Success(r);
            }
            catch (BizException ex)
            {
                return this.FailResult(ex.data, ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                return this.FailResult(null, "系统繁忙，请稍后重试!");
            }
        }
    }
}
